/*
 * QuickSearch.cpp
 *
 *  Created on: 27-08-2013
 *      Author: Krzychu
 */

#include "QuickSearch.h"

#include "../Structures/Config.h"

#include <stdio.h>
#include <string.h>

#define ASIZE 255

QuickSearch::QuickSearch()
{

}

QuickSearch::~QuickSearch()
{

}

std::string QuickSearch::getName()
{
	return "Quick search";
}

int* QuickSearch::preQsBc(std::string pattern)
{
	int* result = new int[ASIZE];

	int patternSize = pattern.size();

	for (int i = 0; i < ASIZE; ++i)
	{
		result[i] = patternSize + 1;
	}
	for (int i = 0; i < patternSize; ++i)
	{
		result[pattern[i]] = patternSize - i;
	}

	return result;
}

searchResult QuickSearch::execute(std::string text, std::string pattern)
{
	searchResult result;
	result.iterationsTaken = 0;

	int textLength = text.length();
	int patternLength = pattern.length();

	const char* textChar = text.c_str();
	const char* patternChar = pattern.c_str();

	/* Preprocessing */
	int* qsBc = preQsBc(pattern);

	/* Searching */
	int j = 0;
	while (j <= textLength - patternLength)
	{
		result.iterationsTaken++;
		if (memcmp(patternChar, textChar + j, patternLength) == 0)
		{
			result.positionsFound.push_back(j);
			if (Config::getInstance()->getFindOneOccurence())
			{
				return result;
			}
		}
		j += qsBc[text[j + patternLength]]; /* shift */
	}

	return result;
}
